package com.c1.client.dialog.r;

import com.c1.client.dialog.BaseButton;
import com.c1.client.dialog.JDialogButtonSupport;
import com.c1.client.pan.Pans;
import com.c1.client.dialog.r.button.RCancelButton;
import com.c1.client.dialog.r.util.ImageUtil;
import com.c1.client.dialog.r.util.SinaRemote;
import com.s.core.root.CodeFeature;
import lombok.Getter;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.Collections;
import java.util.List;

@Getter
public class RDialog extends JDialogButtonSupport implements ActionListener {
    private static final String TITLE = "K线/分时";

    private static final int IMAGE_W = 872;
    private static final int IMAGE_H = 480;
    private static final int W_OFFSET = 50;
    private static final int H_OFFSET = 20;

    private static volatile RDialog me;

    public static RDialog me() {
        if (me == null) {
            synchronized (RDialog.class) {
                if (me == null) {
                    me = new RDialog();
                }
            }
        }
        return me;
    }

    private final RPanel rPanel = new RPanel();
    private final JScrollPane scrollPane = new JScrollPane(rPanel);
    private final JPanel commandArea;

    @Override
    public List<Class<? extends BaseButton>> getBaseButton() {
        return Collections.singletonList(RCancelButton.class);
    }

    private RDialog() {
        super();
        this.setActionListener(this);

        rPanel.setFatherJScrollPane(scrollPane);

        setModal(true);
        setResizable(false);

        setTitle(TITLE);

        add(scrollPane);

        commandArea = new JPanel();
        commandArea.add(get(RCancelButton.class, KeyEvent.VK_C));
        add(commandArea, BorderLayout.SOUTH);
    }

    public void loadImageAndSetVisible() {
        if (setImage()) {
            setVisible(true);
        }
    }

    private boolean setImage() {
        String code = Pans.me().getCurrentPan().code(false);
        String tsCode = CodeFeature.getTsCode(code);
        String fsImageUrl = SinaRemote.getMinImageUrl(code, tsCode);
        String dkImageUrl = SinaRemote.getDailyImageUrl(code, tsCode);
        Image fsImage = ImageUtil.getImageIcon(fsImageUrl, IMAGE_W, IMAGE_H, this);
        if (fsImage == null) {
            return false;
        }
        Image dkImage = ImageUtil.getImageIcon(dkImageUrl, IMAGE_W, IMAGE_H, this);
        if (dkImage == null) {
            return false;
        }
        rPanel.setImage(fsImage, dkImage);
        setSize(IMAGE_W + W_OFFSET,
                2 * IMAGE_H + commandArea.getPreferredSize().height * 2 + H_OFFSET);
        setLocationRelativeTo(null);
        return true;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();
        process(command);
    }
}